<template>
  <div class="login-wrap" @keydown.enter="login">
    <div class="login-con">
      <el-card class="box-card">
        <template #header>
          <span class="login--header">学灯网讲师平台登录</span>
        </template>
        <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          class="login-form"
        >
          <el-form-item prop="mobile">
            <el-input
              v-model="form.mobile"
              autocomplete="off"
              placeholder="请输入手机号"
              class="form--input"
            >
              <template #prefix>
                <span class="svg-container">
                  <svg-icon icon-class="user" />
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              show-password
              autocomplete="off"
              :minlength="3"
              :maxlength="18"
              placeholder="请输入密码"
              class="form--input"
            >
              <template #prefix>
                <span class="svg-container">
                  <svg-icon icon-class="password" />
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              class="login--button"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, unref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { permissionStore } from '@/store/modules/permission'
import { appStore } from '@/store/modules/app'
import wsCache from '@/cache'
import { ElNotification } from 'element-plus'
import { loginUserStore } from './store/loginUser'
import { loginApi } from './api'
import { Message } from '_c/Message'

interface FormModule {
  mobile: string,
  password: string
}
interface RulesModule {
  mobile: any[],
  password: any[]
}

export default defineComponent({
  name: 'Login',
  setup() {
    const { push, addRoute, currentRoute } = useRouter()
    const loginForm = ref<HTMLElement | null>(null)
    const loading = ref<boolean>(false)
    const redirect = ref<string>('')
    watch(() => {
      return currentRoute.value
    }, (route) => {
      redirect.value = (route.query && route.query.redirect) as string
    }, {
      immediate: true
    })
    const form = reactive<FormModule>({
      mobile: '',
      password: ''
    })
    const rules = reactive<RulesModule>({
      mobile: [{ required: true, message: '请输入手机号' }],
      password: [{ required: true, message: '请输入密码' }]
    })
    async function login(): Promise<void> {
      const formWrap = unref(loginForm) as any
      if (!formWrap) return
      loading.value = true
      try {
        formWrap.validate(async(valid: boolean) => {
          if (valid) {
            const formData = unref(form)
            const res = await loginApi({
              data: formData
            })
            if (res.code === 200) {
              const logUser = {
                mobile: res.data.mobile,
                vipId: res.data.vipId,
                vipType: res.data.vipType,
                avatar: res.data.avatar,
                userid: res.data.userid,
                username: res.data.username
              }
              loginUserStore.SetLoginUser(logUser)
              wsCache.set(appStore.userToken, res.data.access_token)
              Message.success(res.message, res)
            } else {
              ElNotification({
                title: '提示',
                message: res.message,
                duration: 60000
              })
              return false
            }

            permissionStore.GenerateRoutes().then(() => {
              permissionStore.addRouters.forEach(async(route: RouteRecordRaw) => {
                await addRoute(route.name!, route) // 动态添加可访问路由表
              })
              permissionStore.SetIsAddRouters(true)
              push({ path: redirect.value || '/' })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } catch (err) {
        console.log(err)
      } finally {
        loading.value = false
      }
    }

    ElNotification({
      title: '提示',
      message: '没有账户，请先到学灯网注册账号并申请开通讲师权限',
      duration: 60000
    })

    return {
      loginForm,
      loading, redirect, form, rules,
      login
    }
  }
})
</script>

<style lang="less" scoped>
.login-wrap {
  width: 100%;
  height: 100%;
  background-image: url('~@/assets/img/login-bg.jpg');
  background-size: cover;
  background-position: center;
  position: relative;
  .box-card {
    width: 400px;
    .login--header {
      font-size: 24px;
      font-weight: 600;
    }
    .svg-container {
      color: #889aa4;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }
    .form--input {
      width: 100%;
      @{deep}(.el-input__inner) {
        padding-left: 40px;
      }
    }
    .login--button {
      width: 100%;
    }
  }
  .login-con {
    position: absolute;
    right: 160px;
    top: 50%;
    transform: translateY(-60%);
  }
}
</style>
